<template>
    <div class="com-table-header-wrap">
        <div class="nomal-search-box">
            <div class="operate-box">
                <template v-if="option.operateData && option.operateData.length">
                    <el-button
                        size="mini"
                        :disabled="item.disabled"
                        type="primary"
                        v-for="(item, index) in option.operateData.slice(0, option.topBtnsLimitNum)"
                        :key="'btn_' + index"
                        @click="operateBtnClick(item)"
                        >{{ item.name }}
                    </el-button>
                    <el-dropdown
                        class="operate-dropdown"
                        v-if="option.operateData.slice(option.topBtnsLimitNum).length > 0"
                        trigger="click"
                        @command="operateBtnClick"
                    >
                        <el-button type="primary" size="mini">
                            更多<i class="el-icon-caret-bottom el-icon--right"></i>
                        </el-button>
                        <el-dropdown-menu slot="dropdown" class="myDropdownBox">
                            <el-dropdown-item
                                v-for="(item, index) in option.operateData.slice(
                                    option.topBtnsLimitNum
                                )"
                                :key="`top-dropdown-item-${index}`"
                                :command="item"
                            >
                                <span>{{ item.name }}</span>
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </template>
            </div>
            <div class="search-box">
                <section class="normal-search-container">
                    <template v-if="!isHighSearchModel">
                        <div class="search-container">
                            <el-select
                                v-model="searchKey"
                                :style="{ width: searchKeyWidth + 'px' }"
                                class="select-search"
                                value-key="colkey"
                                size="mini"
                            >
                                <el-option
                                    v-for="item in option.searchData"
                                    :key="item.colkey"
                                    :label="item.name"
                                    :value="item.colkey"
                                ></el-option>
                            </el-select>
                            <section class="search-conditions">
                                <div class="condition-content">
                                    <template v-if="curSearchItem.type === 'input'">
                                        <el-input
                                            v-model="curSearchItem.searchItemValue"
                                            :class="
                                                curSearchItem.className
                                                    ? curSearchItem.className
                                                    : ''
                                            "
                                            :style="curSearchItem.style ? curSearchItem.tyle : ''"
                                            :placeholder="curSearchItem.placeholder"
                                            @input="
                                                selectValChange(
                                                    curSearchItem.searchItemValue,
                                                    curSearchItem
                                                )
                                            "
                                            size="mini"
                                            clearable
                                        />
                                    </template>
                                    <template v-else-if="curSearchItem.type === 'select'">
                                        <el-select
                                            v-model="curSearchItem.searchItemValue"
                                            :class="
                                                curSearchItem.className
                                                    ? curSearchItem.className
                                                    : ''
                                            "
                                            :style="
                                                'width: 100%;' + curSearchItem.style
                                                    ? curSearchItem.style
                                                    : ''
                                            "
                                            filterable
                                            clearable
                                            size="mini"
                                            @change="(val) => selectValChange(val, curSearchItem)"
                                            :placeholder="curSearchItem.placeholder"
                                        >
                                            <el-option
                                                v-for="item in curSearchItem.selectData"
                                                :key="`list-item-${
                                                    item[curSearchItem.valueKey || 'value']
                                                }`"
                                                :label="item[curSearchItem.labelKey || 'label']"
                                                :value="item[curSearchItem.valueKey || 'value']"
                                            >
                                            </el-option>
                                        </el-select>
                                    </template>
                                    <template v-else-if="curSearchItem.type === 'date'">
                                        <advanced-date-picker
                                            ref="advanceDatePicker"
                                            @selectValChange="
                                                selectValChange(
                                                    $event,
                                                    curSearchItem,
                                                    curSearchItem.colkey
                                                )
                                            "
                                            v-model="curSearchItem.searchItemValue"
                                            className="common-time-picker"
                                            :date-picker="curSearchItem.timeOption.datePicker"
                                            :timeDiff="timeDiff"
                                        />
                                    </template>
                                    <template v-else>
                                        <el-input
                                            v-model="curSearchItem.searchItemValue"
                                            :class="curSearchItem.className"
                                            :style="curSearchItem.style"
                                            clearable
                                            @input="
                                                selectValChange(
                                                    curSearchItem.searchItemValue,
                                                    curSearchItem
                                                )
                                            "
                                            size="mini"
                                            :placeholder="curSearchItem.placeholder"
                                        />
                                    </template>
                                </div>
                            </section>
                        </div>
                        <el-button
                            size="mini"
                            type="primary"
                            @click="nomalSearchClick"
                            style="height: 28px; margin-right: 10px"
                            >搜索</el-button
                        >
                    </template>
                    <div class="highSearch" v-if="option.isShowHighSearch && !isHighSearchModel">
                        <el-button size="mini" type="primary" @click.stop="onVisibleSearch">
                            {{ isHighSearchModel ? '收起高级搜索' : '高级搜索' }}
                            <i
                                :style="{
                                    transform: isHighSearchModel
                                        ? 'rotate(90deg)'
                                        : 'rotate(-90deg)',
                                }"
                                class="el-icon-d-arrow-left"
                            ></i>
                        </el-button>
                    </div>
                </section>
            </div>
        </div>
        <div class="high-search-box" v-if="isHighSearchModel">
            <section class="high-search-container">
                <el-form
                    ref="highSearchForm"
                    :inline="true"
                    label-width="100px"
                    :model="conditions"
                    @submit.native.prevent
                >
                    <div class="conditions-row">
                        <el-form-item
                            v-for="curSearchItem in option.searchData"
                            :key="curSearchItem.colkey"
                            :label="curSearchItem.name"
                            class="condition-item"
                            :style="itemFlex"
                        >
                            <template v-if="curSearchItem.type === 'input'">
                                <el-input
                                    v-model="conditions[curSearchItem.colkey]"
                                    :class="curSearchItem.className ? curSearchItem.className : ''"
                                    :style="curSearchItem.style ? curSearchItem.style : ''"
                                    @input="
                                        selectValChange(
                                            curSearchItem.searchItemValue,
                                            curSearchItem
                                        )
                                    "
                                    :placeholder="curSearchItem.placeholder"
                                    size="mini"
                                    clearable
                                />
                            </template>
                            <template v-else-if="curSearchItem.type === 'select'">
                                <el-select
                                    v-model="conditions[curSearchItem.colkey]"
                                    :class="curSearchItem.className ? curSearchItem.className : ''"
                                    :style="
                                        'width: 100%;' + curSearchItem.style
                                            ? curSearchItem.style
                                            : ''
                                    "
                                    filterable
                                    clearable
                                    size="mini"
                                    @change="(val) => selectValChange(val, curSearchItem)"
                                    :placeholder="curSearchItem.placeholder"
                                >
                                    <el-option
                                        v-for="item in curSearchItem.selectData"
                                        :key="`list-item-${
                                            item[curSearchItem.valueKey || 'value']
                                        }`"
                                        :label="item[curSearchItem.labelKey || 'label']"
                                        :value="item[curSearchItem.valueKey || 'value']"
                                    >
                                    </el-option>
                                </el-select>
                            </template>
                            <template v-else-if="curSearchItem.type === 'date'">
                                <advanced-date-picker
                                    ref="advanceDatePicker"
                                    v-model="conditions[curSearchItem.colkey]"
                                    className="common-time-picker"
                                    @selectValChange="
                                        selectValChange($event, curSearchItem, curSearchItem.colkey)
                                    "
                                    :date-picker="curSearchItem.timeOption.datePicker"
                                />
                            </template>
                            <template v-else>
                                <el-input
                                    v-model="conditions[curSearchItem.colkey]"
                                    :class="curSearchItem.className"
                                    :style="curSearchItem.style"
                                    clearable
                                    size="mini"
                                    @input="
                                        selectValChange(
                                            curSearchItem.searchItemValue,
                                            curSearchItem
                                        )
                                    "
                                    :placeholder="curSearchItem.placeholder"
                                />
                            </template>
                        </el-form-item>
                    </div>
                    <div class="more-option"></div>
                    <el-form-item class="btn-footer">
                        <el-button type="primary" size="mini" @click="highSearchClick"
                            >搜索</el-button
                        >
                        <el-button type="primary" size="mini" @click="highResetClick"
                            >重置</el-button
                        >
                        <el-button
                            size="mini"
                            type="primary"
                            @click.stop="onVisibleSearch"
                            v-if="isHighSearchModel"
                        >
                            {{ isHighSearchModel ? '收起高级搜索' : '高级搜索' }}
                            <i
                                :style="{
                                    transform: isHighSearchModel
                                        ? 'rotate(90deg)'
                                        : 'rotate(-90deg)',
                                }"
                                class="el-icon-d-arrow-left"
                            ></i>
                        </el-button>
                    </el-form-item>
                </el-form>
            </section>
        </div>
    </div>
</template>

<script> 
const AdvancedDatePicker = () => import('../../../packages/components/zComTableHeader/AdvancedDatePicker.vue')
export default {
  name: 'zComTableHeader',
  components: { AdvancedDatePicker, },
  props: {
    option: {
      require: true,
      type: Object,
      default: function () {
        return {
          topBtnsLimitNum: 4,
          itemLimitNum: 3, // 一行可以排列搜索条件个数 
          isShowHighSearch: false,
          searchData: [],
          operateData: [
            { name: '新增', disabled: false }
          ],
        }
      },
    },
    // 与服务器的时间差
    timeDiff: {
      type: Number,
      default: 0
    }
  },
  data () {
    const conditions = this.resetConditions()
    return {
      conditions,
      searchInitData: [],
      isHighSearchModel: false,
      conditionValue: '',
      searchKey: '',
      curSearchItem: {
        colkey: '',
        name: '',
        placeholder: '',
      },
    }
  },
  computed: {
    searchKeyWidth () {
    //   const sizeMeasure = this.getTextWidth()
    //   const size = this.option.searchData.map((v) => sizeMeasure(v.name))
    //   sizeMeasure(null)
    //   const maxLen = Math.max.apply(null, size)
      return 100
    },
    itemFlex () {
      const flex = (100 / (this.option.itemLimitNum || 3)).toFixed(4) + '%'
      return `flex: 0 0 ${flex}`
    },
  },
  watch: {
    searchKey () {
      this.getCurSearchItemByKey()
      this.$emit('colkeyChange', this.curSearchItem)
    },
  },
  created () {
    this.searchInitData = JSON.parse(JSON.stringify(this.option.searchData))
    if (this.option.searchData.length) {
      this.searchKey = this.option.searchData[ 0 ].colkey
    }
    if (!this.option.topBtnsLimitNum) this.option.topBtnsLimitNum = 4
  },
  methods: {
    // 更新配置初始值
    initSearchData (data) {
      this.searchInitData = JSON.parse(JSON.stringify(data))
    },
    // 更新表单对应的键值对
    resetSelectDefualtData (data) {
      /*
        此方法做作用：
            父组件主动更新某一项的 searchItemValue ，此时需要同步修改 this.conditions 的数据
     */
      this.conditions = this.resetConditions(data)
      this.getCurSearchItemByKey()
    },
    selectValChange (val, item, colkey) {
      if (val && val.type && val.type === 'time') {
        // 对时间控件特殊处理
        this.conditions[ colkey ] = val.searchItemValue
        this.$emit('selectValChange', val)
      } else {
        item.searchItemValue = val
        this.$emit('selectValChange', item)
      }
    },
    copyArr (arr) {
      const res = []
      for (let i = 0; i < arr.length; i++) {
        res.push(arr[ i ])
      }
      return res
    },
    resetConditions (data) {
      const conditions = {}
      // data有值，代表是由 resetSelectDefualtData 方法触发，即 conditions 需要从 this.option.searchData 获取最新数据
      let conditionsArr = []
      if (data) {
        conditionsArr = data && data.length ? this.option.searchData : this.searchInitData
      } else {
        conditionsArr = this.searchInitData && this.searchInitData.length ? this.searchInitData : this.option.searchData
      }
      if (conditionsArr.length) {
        for (const searchItem of conditionsArr) {
          conditions[ searchItem.colkey ] = searchItem.searchItemValue
        }
      }
      return conditions
    },
    highSearchClick () {
      this.$emit('highSearchClick', this.conditions)
      this.$emit('search', this.conditions, 'high')
    },
    highResetClick () {
      this.conditions = this.resetConditions()

      // 重置时间插件
      let arr = this.$refs.advanceDatePicker
      arr.forEach(x => {
        x.showDatePicker = true
        x.setDefaultValue(x.noChangeValue)
      })
      // 重置时间插件 end 

      this.$emit('highResetClick', this.conditions)
    },
    // 初始化数据 
    initOptionData () {
      this.option.searchData = JSON.parse(JSON.stringify(this.searchInitData))
      if (this.option.searchData.length) {
        this.searchKey = this.searchInitData[ 0 ].colkey
        this.curSearchItem = { ...this.searchInitData[ 0 ] }
      }
    },
    onVisibleSearch () {
      this.initOptionData()
      this.conditions = this.resetConditions()
      this.$forceUpdate()
      this.isHighSearchModel = !this.isHighSearchModel
      this.$emit('onVisibleSearch', this.isHighSearchModel)
    },
    getCurSearchItemByKey () {
      this.curSearchItem = { colkey: '', name: '', placeholder: '', searchItemValue: '', }
      if (this.searchInitData.length) {
        const filterData = this.searchInitData.filter((item) => {
          return item.colkey === this.searchKey
        })
        if (filterData.length) {
          this.curSearchItem = { ...filterData[ 0 ] }
        }
      }
    },
    // getTextWidth () {
    //   let dom = document.createElement('span')
    //   dom.style.display = 'inline-block'
    //   document.body.appendChild(dom)
    //   return (str = '') => {
    //     if (str) {
    //       dom.textContent = str
    //       return dom.clientWidth
    //     } else {
    //       document.body.removeChild(dom)
    //       dom = null
    //     }
    //   }
    // },
    nomalSearchClick () {
      const curSearchItemCopy = { ...this.curSearchItem }
      if (this.curSearchItem.type === 'date') {
        const timeVal = this.$refs.advanceDatePicker.getTimeCalculation()
        curSearchItemCopy.searchItemValue = timeVal
      }
      let { colkey, searchItemValue } = curSearchItemCopy
      let obj = {}
      obj[ colkey ] = searchItemValue
      this.$emit('nomalSearchClick', curSearchItemCopy)
      this.$emit('search', obj, 'normal')
    },
    operateBtnClick (item) {
      if (item.disabled) {
        this.$message.warning('此按钮已禁用')
        return
      }
      this.$emit('operateBtnClick', item)
    },
  },
}
</script>
<style lang="scss" scoped>
.com-table-header-wrap {
    padding: 10px;
    box-sizing: border-box;
    .nomal-search-box {
        flex-shrink: 0;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .operate-box {
            font-size: 0;
            .el-button {
                margin-left: 10px !important;
                &:first-child {
                    margin-left: 0 !important;
                }
            }
            .operate-dropdown {
                // vertical-align: middle;
                margin-left: 10px;
            }
        }
        .search-box {
            flex-shrink: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            .normal-search-container {
                ::v-deep .el-input .el-input__inner {
                    border: none;
                }
            }
            .normal-search-container {
                display: flex;
                align-items: center;
                .search-container {
                    border: 1px solid #dcdcdc;
                    border-radius: 4px;
                    margin-right: 10px;
                    height: 28px;
                    overflow: hidden;
                    .select-search {
                        display: inline-block;
                    }
                }
                .search-conditions {
                    width: 220px;
                    flex: 1;
                    vertical-align: top;
                    display: inline-block;
                    position: relative;
                    line-height: 28px;
                    &:before {
                        content: '';
                        width: 1px;
                        height: 14px;
                        position: absolute;
                        top: 0;
                        bottom: 0;
                        margin: auto;
                        left: 0;
                        z-index: 9;
                        background: #dcdcdc;
                        display: block;
                    }
                    .condition-content {
                        line-height: 25px;
                        overflow: hidden;
                        ::v-deep .el-select__tags {
                            max-height: 27px;
                            overflow-y: auto;
                        }
                        ::v-deep .el-select {
                            width: 100%;
                        }
                    }
                }
            }
        }
    }
    .high-search-box {
        .high-search-container {
            // padding-top: 20px;
            .conditions-row {
                max-height: 220px;
                overflow: auto;
                display: flex;
                flex-wrap: wrap;
                .condition-item {
                    display: inline-block;
                    flex: 0 0 33.3333%;
                    padding: 0 20px 0;
                    box-sizing: border-box;
                }
            }
            .btn-footer {
                box-sizing: border-box;
                padding: 0 0 0 118px;
                .el-button {
                    margin-right: 10px;
                }
            }
            ::v-deep .el-form-item {
                width: 100%;
                margin-bottom: 10px;
                margin-right: 0px;
                .el-form-item__label {
                    text-align: left;
                    display: inline-block;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                }
                .el-form-item__content {
                    font-size: 0;
                    width: calc(100% - 100px);
                    .el-select {
                        width: 100%;
                    }
                }
            }
        }
        .common-time-picker {
            width: 100%;
        }
    }
}
</style>